package org.linlinjava.litemall.wx.aiweb;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LemonlaActorMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.HomeCacheManager;
import org.linlinjava.litemall.wx.service.WxGrouponRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 首页服务
 */
@RestController
@RequestMapping("/wx/ai/home")
@Validated
public class WxAiHomeController {
    private final Log logger = LogFactory.getLog(WxAiHomeController.class);

    @Autowired
    private LitemallAdService adService;
    @Autowired
    private LemonlaActorService actorService;

    @Autowired
    private LemonlaCategoryService categoryService;
    @Autowired
    private LitemallCollectService collectService;

    @GetMapping("/cache")
    public Object cache(@NotNull String key) {
        if (!key.equals("litemall_cache")) {
            return ResponseUtil.fail();
        }

        // 清除缓存
        HomeCacheManager.clearAll();
        return ResponseUtil.ok("缓存已清除");
    }

    /**
     * 首页推荐数据
     * @param userId 当用户已经登录时，非空。未登录状态为null
     * @return 首页数据
     */
    @GetMapping("/recommend")
    public Object recommend(@LoginUser Integer userId) {
        //优先从缓存中读取
        if (HomeCacheManager.hasData(HomeCacheManager.RECOMMEND)) {
            return ResponseUtil.ok(HomeCacheManager.getCacheData(HomeCacheManager.RECOMMEND));
        }

        List<LitemallAd> litemallAds = adService.queryIndex();
        Map<String, Object> entity = new HashMap<>();
        try {
            entity.put("recommend", litemallAds);
            //缓存数据
            HomeCacheManager.loadData(HomeCacheManager.RECOMMEND, entity);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseUtil.ok(entity);
    }

    /**
     * 首页分类数据
     * @param userId 当用户已经登录时，非空。未登录状态为null
     * @return 首页数据
     */
    @GetMapping("/category")
    public Object category(@LoginUser Integer userId) {
        //优先从缓存中读取
        if (HomeCacheManager.hasData(HomeCacheManager.CATEGORY)) {
            return ResponseUtil.ok(HomeCacheManager.getCacheData(HomeCacheManager.CATEGORY));
        }

        List<Map> categoryList = getCategoryList(userId,100);
        Map<String, Object> entity = new HashMap<>();
        try {
            entity.put("category", categoryList);
            //缓存数据
            HomeCacheManager.loadData(HomeCacheManager.CATEGORY, entity);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
//        finally {
//            executorService.shutdown();
//        }
        return ResponseUtil.ok(entity);
    }

    /**
     * 首页分类数据
     * @param userId 当用户已经登录时，非空。未登录状态为null
     * @return 首页数据
     */
    @GetMapping("/category_simple")
    public Object simpleCat(@LoginUser Integer userId) {

        List<Map> categoryList = getCategoryList(userId,4);
        Map<String, Object> entity = new HashMap<>();
        try {
            entity.put("category", categoryList);
            //缓存数据
            HomeCacheManager.loadData(HomeCacheManager.CATEGORY, entity);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
//        finally {
//            executorService.shutdown();
//        }
        return ResponseUtil.ok(entity);
    }


    private List<Map> getCategoryList(Integer userId,Integer num) {
        List<Map> categoryList = new ArrayList<>();
        List<LemonlaCategory> catL1List = categoryService.queryL1(0, num);
        for (LemonlaCategory catL1 : catL1List) {
            List<LemonlaActor> actors;
            actors = actorService.queryByCategory(catL1.getId(), 0, num);
            for (LemonlaActor actor : actors) {
                if (userId!=null) {
                    LitemallCollect litemallCollect = collectService.queryByTypeAndValue(userId, (byte) 0, actor.getId());
                    if (litemallCollect!=null) {
                        actor.setStatus((byte) 1);
                    }
                }
            }
            Map<String, Object> catGoods = new HashMap<>();
            catGoods.put("id", catL1.getId());
            catGoods.put("name", catL1.getName());
            catGoods.put("actorList", actors);
            categoryList.add(catGoods);
        }
        return categoryList;
    }

    /**
     * 商城介绍信息
     * @return 商城介绍信息
     */
    @GetMapping("/about")
    public Object about() {
        Map<String, Object> about = new HashMap<>();
        about.put("name", SystemConfig.getMallName());
        about.put("address", SystemConfig.getMallAddress());
        about.put("phone", SystemConfig.getMallPhone());
        about.put("qq", SystemConfig.getMallQQ());
        about.put("longitude", SystemConfig.getMallLongitude());
        about.put("latitude", SystemConfig.getMallLatitude());
        return ResponseUtil.ok(about);
    }
}